package com.steven.im.ui.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.CardView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.*;
import butterknife.BindView;
import butterknife.OnClick;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.steven.im.App;
import com.steven.im.R;
import com.steven.im.base.BaseActivity;
import com.steven.im.entity.BaseEntity;
import com.steven.im.entity.SubmitOrderEntity;
import com.steven.im.net.MyCallback;
import com.steven.im.net.Task;
import com.steven.im.utils.PayResult;
import com.steven.im.utils.ScreenUtil;
import com.steven.im.utils.StatusBarUtil;
import com.steven.im.utils.ToastUtil;
import com.tencent.mm.opensdk.modelpay.PayReq;
import retrofit2.Response;

import java.util.Map;

/**
 * Created by Steven on 2019/1/11.
 */
public class ConfirmOrderActivity extends BaseActivity {

    @BindView(R.id.cb_wxpay)
    CheckBox cbWxpay;
    @BindView(R.id.cb_alipay)
    CheckBox cbAlipay;
    /**
     * 有地址信息的
     */
    @BindView(R.id.ll_address)//有默认地址栏的
            LinearLayout ll_address;
    @BindView(R.id.iv_back)//有地址栏的返回箭头
            ImageView ivBack;
    @BindView(R.id.tv_goodsPeople)//收货人姓名电话
            TextView tv_goodsPeople;
    @BindView(R.id.tv_goodsAccount)//收货地址信息
            TextView tv_goodsAccount;

    @BindView(R.id.img)//显示大图
            ImageView img;


    @BindView(R.id.tv_shichangjia)//市场价
            TextView tv_shichangjia;
    @BindView(R.id.tv_chengjiaojia)//成交价
            TextView tv_chengjiaojia;
    @BindView(R.id.tv_shijizhifu)//实际支付
            TextView tv_shijizhifu;

    @BindView(R.id.tv_name)//商品名称
            TextView tvName;
    @BindView(R.id.tv_putong)//普通商品
            TextView tv_putong;
    @BindView(R.id.tv_realPay)//实际支付
            TextView tv_realPayl;
    @BindView(R.id.card3)
    CardView ll_payWay;
    /**
     * 没地址信息的
     */
    @BindView(R.id.ll_noAddress)
    LinearLayout ll_noAddress;
    private Activity activity;
    private String goodsId = "";//商品Id
    private String salesType = "";//商品类型
    private String orderId;//订单id
    private String addressId = "";//地址Id
    private String paymentCode;//支付方式
    private int ALIPAY = 1;
    private int WEICHATPAY = 2;
    private String orderType;//订单类型 0.普通；1.充值；2.竞拍；3.差价购买
    private String myType;//区分商品 订单的跳转 （内部变量）
    private boolean isHaveAddress = false;//默认false
    private boolean isFirst = true;//默认是不是第一次加载
    private boolean isPay = false;//判断是否关闭当前页面
    private String realPay = "-1";//默认是不等于0的

    @Override
    public void setListen() {
        cbWxpay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {//选中微信支付
                    cbAlipay.setChecked(false);
                }
            }
        });
        cbAlipay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {//支付宝支付
                    cbWxpay.setChecked(false);
                }
            }
        });

    }

    @Override
    public void setTitleBarColor() {
        activity = ConfirmOrderActivity.this;
        //设置状态栏颜色
        StatusBarUtil.StatusBarDarkMode(activity);
        //设置状态栏颜色
        StatusBarUtil.setStatusBarColor(activity, R.drawable.confirm_order_shape);
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_confirmorder;
    }

    @Override
    public void initView() {
    }

    @Override
    public void initData() {
        //类型
        myType = getIntent().getStringExtra("my_type");
        goodsId = getIntent().getStringExtra("Id");
        salesType = getIntent().getStringExtra("salesType");
    }

    @OnClick({R.id.title_left, R.id.tv_topay, R.id.ll_noAddress, R.id.ll_address, R.id.iv_back})
    public void onViewClicked(View view) {
        if (ScreenUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.title_left:
                finish();
                break;
            case R.id.tv_topay://立即支付
                if (!isHaveAddress) {
                    ToastUtil.showShort(this, "请添加默认地址！");
                } else {
                    if ("0.00".equals(realPay) || "0".equals(realPay)) {
                        //使用购物币支付
                        buyNowCurrency();
                    } else {
                        buyNow();
                    }
                }
                break;
            case R.id.ll_noAddress://添加地址
            case R.id.ll_address://修改地址
            case R.id.iv_back:
//                startActivity(new Intent(activity, AddaddrActivity.class).putExtra("addressId", addressId));
                startActivity(new Intent(activity, MyaddrActivity.class).putExtra("change", true));
                break;
        }
    }

    private void buyNowCurrency() {
        Task.getApiService().submitOrder(orderId, addressId, paymentCode).enqueue(new MyCallback<BaseEntity>(ConfirmOrderActivity.this) {
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                if ("0".equals(response.body().getCode())) {
                    ToastUtil.showShort(App.getContext(), response.body().getMessage());
                    finish();
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void onResume() {
        super.onResume();
        if (isFirst) {
            isFirst = false;
            switch (myType) {
                case "good":
                    goodsInit(goodsId, salesType);
                    break;
                case "order":
                    orderInit(goodsId, salesType);
                    break;
            }
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        String my_addressId = intent.getStringExtra("addressId");
        String name = intent.getStringExtra("name");
        String phone = intent.getStringExtra("phone");
        String address = intent.getStringExtra("address");
        if (!my_addressId.equals("")) {
            isHaveAddress = true;
            addressId = my_addressId;
            ll_address.setVisibility(View.VISIBLE);
            ivBack.setVisibility(View.VISIBLE);
            ll_noAddress.setVisibility(View.GONE);
            tv_goodsPeople.setText("收货人：" + name + phone);
            tv_goodsAccount.setText("收货地址：" + address);
        } else {
            switch (myType) {
                case "good":
                    goodsInit(goodsId, salesType);
                    break;
                case "order":
                    orderInit(goodsId, salesType);
                    break;
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (isPay)
            finish();
    }

    //点击立即支付
    private void buyNow() {
        if (cbWxpay.isChecked()) {
            paymentCode = "WeChat";
            if (!App.getWXAPI().isWXAppInstalled()) {
                ToastUtil.showShort(App.getContext(), "未安装微信或版本号太低");
                return;
            }
        } else {
            paymentCode = "Alipay";
        }
        Task.getApiService().submitOrder(orderId, addressId, paymentCode).enqueue(new MyCallback<BaseEntity>(ConfirmOrderActivity.this) {
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                if ("0".equals(response.body().getCode())) {
                    switch (paymentCode) {
                        case "WeChat"://微信支付
                            if (App.getWXAPI().isWXAppInstalled()) {
                                isPay = true;
                                showWeChat(response.body().getResult());
                            } else {
                                ToastUtil.showShort(App.getContext(), "未安装微信或版本号太低");
                            }
                            break;
                        case "Alipay"://支付宝支付
                            showAlipay(response.body().getResult().get("alipay_order_sign") + "");
                            break;
                    }
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    //调起微信支付
    private void showWeChat(final JSONObject body) {

        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayReq request = new PayReq();
                request.appId = body.getString("appid");
                request.partnerId = body.getString("mch_id");
                request.prepayId = body.getString("prepay_id");
                request.packageValue = body.getString("package");
                request.nonceStr = body.getString("nonce_str");
                request.timeStamp = body.getString("timestamp");
                request.sign = body.getString("sign") + "";
                App.getWXAPI().sendReq(request);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    //调起支付宝支付
    private void showAlipay(final String orderInfo) {

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(activity);
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = ALIPAY;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /*
    支付宝支付
     */
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {   //支付宝支付
            switch (msg.what) {
                case 1: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    Log.e("TAG", "handleMessage: " + resultStatus);
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(ConfirmOrderActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(ConfirmOrderActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    finish();
                    break;
                }
                default:
                    break;
            }
        }
    };

    //生成从订单来的 商品信息
    private void orderInit(String id, String type) {
        Task.getApiService().oredrInit(id, type).enqueue(new MyCallback<BaseEntity>(this) {
            @SuppressLint("SetTextI18n")
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                try {
                    if ("0".equals(response.body().getCode())) {
                        tvName.setText(response.body().getResult().getString("goodsTitle"));
                        Gson gson = new Gson();
                        orderId = response.body().getResult().get("orderId") + "";
                        orderType = response.body().getResult().get("orderType") + "";
                        realPay = response.body().getResult().getString("paymentAmount");
                        if ("0.00".equals(realPay) || "0".equals(realPay))
                            ll_payWay.setVisibility(View.GONE);
                        if (response.body().getResult().containsKey("defaultAddress")) {
                            isHaveAddress = true;
                            SubmitOrderEntity.ResultBean resultBean = gson.fromJson(response.body().getResult().toJSONString(), SubmitOrderEntity.ResultBean.class);
                            addressId = resultBean.getDefaultAddress().getAddressId();
                            ll_address.setVisibility(View.VISIBLE);
                            ivBack.setVisibility(View.VISIBLE);
                            ll_noAddress.setVisibility(View.GONE);
                            tv_goodsPeople.setText("收货人：" + resultBean.getDefaultAddress().getReceiver() + " " + resultBean.getDefaultAddress().getMobile());
                            tv_goodsAccount.setText("收货地址：" + resultBean.getDefaultAddress().getAddress());
                        } else {
                            isHaveAddress = false;
                            ll_address.setVisibility(View.GONE);
                            ivBack.setVisibility(View.GONE);
                            ll_noAddress.setVisibility(View.VISIBLE);
                        }
                        Picasso.with(App.getContext()).load(response.body().getResult().get("previewImage") + "").into(img);
                        setCenterPreview(response);
                        JSONArray array = response.body().getResult().getJSONArray("paymentList");
                        String string_1 = array.getString(0);
                        String string_2 = array.getString(0);
                        JSONObject fromObject = JSON.parseObject(string_1);
                        JSONObject fromObject_1 = JSON.parseObject(string_2);
                        String status = fromObject.getString("paymentStatus");
                        if ("1".equals(status)) {
                            paymentCode = fromObject.getString("paymentCode");
                            cbAlipay.setChecked(true);
                            cbWxpay.setChecked(false);
                        } else {
                            paymentCode = fromObject_1.getString("paymentCode");
                            cbAlipay.setChecked(false);
                            cbWxpay.setChecked(true);
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(Throwable t) {
            }
        });
    }

    //判断 是竞拍商品  还是  普通商品
    @SuppressLint("SetTextI18n")
    private void setCenterPreview(Response<BaseEntity> response) {
        switch (salesType) {
            case "0"://普通商品
                tv_putong.setText("购物币：");
                tv_shichangjia.setText("￥" + response.body().getResult().get("discountPrice") + "");
                tv_chengjiaojia.setText("￥" + response.body().getResult().get("shoppingCurrency") + "");
                tv_shijizhifu.setText("￥" + response.body().getResult().get("paymentAmount") + "");
                tv_realPayl.setText("￥" + response.body().getResult().get("paymentAmount") + "");
                break;
            case "3":
                tv_putong.setText("幸运豆：");
                tv_shichangjia.setText("￥" + response.body().getResult().get("discountPrice") + "");
                tv_chengjiaojia.setText("￥" + response.body().getResult().get("biddingCurrency") + "");
                tv_shijizhifu.setText("￥" + response.body().getResult().get("paymentAmount") + "");
                tv_realPayl.setText("￥" + response.body().getResult().get("paymentAmount") + "");
                break;
            default:
//            case "1"://竞拍商品
//            case "2":
                tv_putong.setText("成交价：");
                tv_shichangjia.setText("￥" + response.body().getResult().get("originalPrice") + "");
                tv_chengjiaojia.setText("￥" + response.body().getResult().get("biddingPrice") + "");
                tv_shijizhifu.setText("￥" + response.body().getResult().get("paymentAmount") + "");
                tv_realPayl.setText("￥" + response.body().getResult().get("paymentAmount") + "");
                break;

        }
    }

    /**
     * 生成普通商品订单
     */
    private void goodsInit(String id, String type) {
        Task.getApiService().goodsInit(id, type).enqueue(new MyCallback<BaseEntity>(this) {
            @SuppressLint("SetTextI18n")
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                try {
                    if ("0".equals(response.body().getCode())) {
                        tvName.setText(response.body().getResult().getString("goodsTitle"));
                        Gson gson = new Gson();
                        orderId = response.body().getResult().get("orderId") + "";
                        orderType = response.body().getResult().get("orderType") + "";
                        realPay = response.body().getResult().getString("paymentAmount");
                        if ("0.00".equals(realPay) || "0".equals(realPay))
                            ll_payWay.setVisibility(View.GONE);
                        if (response.body().getResult().containsKey("defaultAddress")) {
                            isHaveAddress = true;
                            SubmitOrderEntity.ResultBean resultBean = gson.fromJson(response.body().getResult().toJSONString(), SubmitOrderEntity.ResultBean.class);
                            addressId = resultBean.getDefaultAddress().getAddressId();
                            ll_address.setVisibility(View.VISIBLE);
                            ivBack.setVisibility(View.VISIBLE);
                            ll_noAddress.setVisibility(View.GONE);
                            tv_goodsPeople.setText("收货人：" + resultBean.getDefaultAddress().getReceiver() + " " + resultBean.getDefaultAddress().getMobile());
                            tv_goodsAccount.setText("收货地址：" + resultBean.getDefaultAddress().getAddress());
                        } else {
                            isHaveAddress = false;
                            ll_address.setVisibility(View.GONE);
                            ivBack.setVisibility(View.GONE);
                            ll_noAddress.setVisibility(View.VISIBLE);
                        }
                        Picasso.with(App.getContext()).load(response.body().getResult().get("previewImage") + "").into(img);
                        setCenterPreview(response);
                        JSONArray array = response.body().getResult().getJSONArray("paymentList");
                        String string_1 = array.getString(0);
                        String string_2 = array.getString(0);
                        JSONObject fromObject = JSON.parseObject(string_1);
                        JSONObject fromObject_1 = JSON.parseObject(string_2);
                        String status = fromObject.getString("paymentStatus");
                        if ("1".equals(status)) {
                            paymentCode = fromObject.getString("paymentCode");
                            cbAlipay.setChecked(true);
                            cbWxpay.setChecked(false);
                        } else {
                            paymentCode = fromObject_1.getString("paymentCode");
                            cbAlipay.setChecked(false);
                            cbWxpay.setChecked(true);
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

}